﻿using System;
using System.IO;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal class DeferredIntWriter
    {
        private readonly long position;
        private readonly BinaryWriter writer;

        public DeferredIntWriter(BinaryWriter writer)
        {
            position = writer.BaseStream.Position;
            this.writer = writer;
            writer.Write((int)0);
        }

        public void Write(int i)
        {
            long lastPosition = writer.BaseStream.Position;
            writer.BaseStream.Position = position;
            writer.Write(i);
            writer.BaseStream.Position = lastPosition;
        }

        public IDisposable GetLength()
        {
            return new GetLengthAction(this);
        }

        #region Nested type: GetLengthAction

        private class GetLengthAction : IDisposable
        {
            private readonly DeferredIntWriter _deferredIntWriter;
            private readonly long startPosition;

            public GetLengthAction(DeferredIntWriter deferredIntWriter)
            {
                _deferredIntWriter = deferredIntWriter;
                startPosition = _deferredIntWriter.writer.BaseStream.Position;
            }

            #region IDisposable Members

            public void Dispose()
            {
                long endPosition = _deferredIntWriter.writer.BaseStream.Position;
                var diff = (int) (endPosition - startPosition);
                _deferredIntWriter.Write(diff);
            }

            #endregion
        }

        #endregion
    }
}